package com.code.cheney.shiro.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.code.cheney.shiro.dao.RoleDao;
import com.code.cheney.shiro.entity.Role;
import com.code.cheney.shiro.service.RoleService;

/**
 * 
 * Project: shiro Class: RoleServiceImpl Description:
 * 
 * @author: Cheney
 * @Date 2016年6月30日 下午9:16:45
 * @version 1.0
 * 
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;

	public Role createRole(Role role) {
		Long id = roleDao.createRole(role);
		role.setId(id);
		return role;
	}

	public void deleteRole(Long roleId) {
		roleDao.deleteRole(roleId);
	}

	/**
	 * 添加角色-权限之间关系
	 * 
	 * @param roleId
	 * @param permissionIds
	 */
	public void correlationPermissions(Long roleId, Long... permissionIds) {
		if(permissionIds == null || permissionIds.length == 0) {
            return;
        }
		for(Long permissionId : permissionIds) {
            if(!exists(roleId, permissionId)) {
            	roleDao.correlationRoles(roleId, permissionId);
            }
        }
	}

	/**
	 * 移除角色-权限之间关系
	 * 
	 * @param roleId
	 * @param permissionIds
	 */
	public void uncorrelationPermissions(Long roleId, Long... permissionIds) {
		if(permissionIds == null || permissionIds.length == 0) {
            return;
        }
		for(Long permissionId : permissionIds) {
            if(exists(roleId, permissionId)) {
            	roleDao.uncorrelationRoles(roleId, permissionId);
            }
        }
	}
	
	private boolean exists(Long userId, Long roleId) {
        return roleDao.exists(userId, roleId);
    }

}
